package com.hzy.fivepalace.admin.interceptors;

import com.alibaba.fastjson.JSON;
import com.hzy.fivepalace.admin.annotation.Login;
import com.hzy.fivepalace.admin.service.AdminTokenManager;
import com.hzy.fivepalace.common.consts.CommConsts;
import com.hzy.fivepalace.common.service.redis.RedisCache;
import com.hzy.fivepalace.common.util.ResponseUtil;
import com.hzy.fivepalace.db.domain.DtsAdmin;
import com.hzy.fivepalace.db.service.DtsAdminService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;

/**
 * 权限认证拦截器
 */
public class AppInterceptor implements HandlerInterceptor {

    private static Logger log = LoggerFactory.getLogger(AppInterceptor.class);

    @Resource
    private RedisCache redisCache;


    @Autowired
    private DtsAdminService adminService;


    @Resource
    private AdminTokenManager adminTokenManager;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
        if (!(handler instanceof HandlerMethod)) {
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Method method = handlerMethod.getMethod();
        //以下操作为判断当前请求是否需要认证
        Login login = method.getAnnotation(Login.class);
        boolean isRequiredLogin = false;
        //优先判断方法注解
        if (login != null) {
            isRequiredLogin = login.authentication();
        } else {//再判断类注解
            login = handlerMethod.getMethod().getDeclaringClass().getAnnotation(Login.class);
            if (login != null) {
                isRequiredLogin = login.authentication();
            }
        }

        response.setCharacterEncoding("UTF-8");

        //不需要认证就直接返回出去
        if (!isRequiredLogin) {
            return true;
        }
        //用户的授权token
        String token = request.getHeader(CommConsts.ADMIN_LOGIN_TOKEN_KEY);
        if (StringUtils.isBlank(token)) {
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().print(JSON.toJSONString(ResponseUtil.unlogin("未登录")));
            return false;
        }
        Integer userId = adminTokenManager.getAdminId(token);
        if (null == userId) {
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().print(JSON.toJSONString(ResponseUtil.unlogin("未登录或登录过期")));
            return false;
        }

        DtsAdmin admin = adminService.selectById(userId);
        if (null == admin) {
            adminTokenManager.removeToken(token);
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().print(JSON.toJSONString(ResponseUtil.unlogin("账号不存在,请重新登录")));
            return false;
        }
        if (admin.getDeleted()) {
            adminTokenManager.removeToken(token);
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().print(JSON.toJSONString(ResponseUtil.unlogin("账号已被删除,请重新登录")));
            return false;
        }

        request.setAttribute(CommConsts.ADMIN_Id_KEY, userId);
        request.setAttribute(CommConsts.ADMIN_INFO_KEY, admin);
        request.setAttribute(CommConsts.ADMIN_TOKEN_KEY, token);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object o, ModelAndView modelAndView) {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object o, Exception e) {

    }

}
